<!-- 任务分配弹窗 -->

<template>
  <el-dialog :close-on-click-modal="false" :title="$tt('label_multiple_box_packing')" :visible.sync="visible"
    custom-class="dialog_big">

    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="正常打包" name="single">
        <el-form :label-width="$globalCss.formLabelWidth_default" :model="singlePackForm" ref="packForm" class="mg_t2"
          :rules="BoxPackiRules">
          <el-form-item :label="$tt('text_has_select_order')" v-if="selectOrderList.length">
            <ex_super_table v-bind="OrderTableOption" :data="selectOrderList" max-height="300" />
            <div><i class="el-icon-warning color_warning el-icon--left"></i><span class="color_info">
                {{ $tt('tip_add_box_need_select_order_in') }}</span>
            </div>
          </el-form-item>
          <div class="flex_row_wrap">
            <el-form-item :label="$tt('label_package_code')" prop="packageNo" class="flex_cell">
              <div class="flex_row">
                <ex_super_input v-model="singlePackForm.packageNo" :disabled="true" class="form_input_small">
                </ex_super_input>
                <el-button type="text" @click="packingGenerate()" class="mg_l2">
                  {{ $tt('生成包号') }}</el-button>
              </div>
            </el-form-item>
            <el-form-item :label="$tt('label_pack_material')" prop="packagingId" class="flex_cell">
              <pack_material_cascader class="form_input_small" :packId.sync="singlePackForm.packagingId"
                :packName.sync="singlePackForm.packagingName" :typeId.sync="singlePackForm.packagingTypeId"
                :typeName.sync="singlePackForm.packagingTypeName" />
            </el-form-item>
          </div>
          <div class="flex_row_wrap">
            <el-form-item :label="$tt('label_weight')" prop="weight" class="flex_cell">
              <ex_super_input v-model="singlePackForm.weight" class="form_input_small" append='KG'
                appendClass='input_slot_div_mini'>
              </ex_super_input>
            </el-form-item>
            <el-form-item :label="$tt('label_length')" prop="length" class="flex_cell">
              <ex_super_input v-model="singlePackForm.length" class="form_input_small" append='cm'
                appendClass='input_slot_div_mini'>
              </ex_super_input>
            </el-form-item>
          </div>
          <div class="flex_row_wrap">
            <el-form-item :label="$tt('label_width')" prop="width" class="flex_cell">
              <ex_super_input v-model="singlePackForm.width" class="form_input_small" append='cm'
                appendClass='input_slot_div_mini'>
              </ex_super_input>
            </el-form-item>
            <el-form-item :label="$tt('label_height')" prop="height" class="flex_cell">
              <ex_super_input v-model="singlePackForm.height" class="form_input_small" append='cm'
                appendClass='input_slot_div_mini'>
              </ex_super_input>
            </el-form-item>
          </div>

          <el-form-item :label="$tt('label_inner_box_number')">
            <el-row>
              <el-col :span="10">
                <ex_super_input v-model="packTempBoxNumber"></ex_super_input>
              </el-col>
              <el-col :span="6" :offset="1">
                <el-button type="primary" @click="packingBoxAdd">
                  {{ $tt('label_new') }}</el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item prop="boxNoList" :label="$tt('label_box_number_list')">
            <ex_super_table :data="singlePackForm.boxNoList" v-bind="BoxTableOption" />
          </el-form-item>
        </el-form>


      </el-tab-pane>
      <el-tab-pane label="批量打包" name="multiple">
        <el-form :label-width="$globalCss.formLabelWidth_default" :model="batchPackForm" ref="batchForm" class="mg_t2"
          :rules="BatchPackiRules">
          <el-form-item :label="$tt('文件上传')">
            <el-upload ref="upload" :show-file-list="false"
              action="/wms-api/inbound/WmsInboundTransitPackagingRpc/importPackingBoxDetail.json" style="display: inline;"
              :on-success="uploadExcelSuccess" :on-error="uploadExcelError" :before-upload="beforeUpload">
              <el-button slot="trigger" size="mini" type="primary">导入Excel</el-button>
            </el-upload>
            <select_file_temp service="WMS" module="TRANSIT_PACKING_BOX_DETAIL" system="WMS" :label="$tt('下载模板')"
              :title="$tt('下载模板') + '/' + $enumShow('TRANSIT_PACKING_BOX_DETAIL', 'BaseWmsModuleEnum')" />
          </el-form-item>
          <el-form-item prop="packingParamList" :label="$tt('label_box_number_list')">
            <ex_super_table :data="batchPackForm.packingParamList" v-bind="BatchTableOption" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <span slot="footer" class="dialog_footer">
      <el-button @click="visible = false">{{ $tt('label_cancel') }}</el-button>
      <el-button type="primary" @click="submitPack">{{ $tt('label_submit') }}</el-button>
    </span>

  </el-dialog>
</template>

<script>
import pack_material_cascader from '@/component/wms/pack_material_cascader.vue';
import select_file_temp from '@/component/base/select_file_temp'
import Schema from 'async-validator'
const default_dialogPackingForm = {
  packagingTypeId: "",
  packagingTypeName: "",
  packagingId: "",
  packagingName: "",
  packageNo: "",
  length: "",
  width: "",
  height: "", weight: "",
  boxNoList: [],
  receivingIdList: [],
}
export default {
  components: { pack_material_cascader, select_file_temp, },
  data() {
    return {
      activeTab: 'single',
      visible: false,

      loading: false,

      packTempBoxNumber: "",
      selectOrderList: [],
      singlePackForm: _.cloneDeep(default_dialogPackingForm),
      OrderTableOption: {
        model: [
          { key: 'code', label: 'label_inbound_code' },
          { key: 'receivingOrderCode', label: 'label_order_code' },
        ]
      },
      BoxTableOption: {
        height: 250,
        model: [
          { label: 'label_box_code', formatter: (r, c, v) => r },
          {
            type: 'operate', width: 160, operate: [
              {
                label: "label_remove", class: 'button_text_danger',
                click: (row, i) => {
                  this.singlePackForm.boxNoList.splice(i, 1)
                }
              },
            ]
          }
        ]
      },
      BoxPackiRules: {
        packagingTypeId: [{ required: true, message: this.$tt('packagingType_validate_error'), trigger: 'change' }],
        packagingId: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' }],
        packageNo: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' }],
        boxNoList: [{ type: 'array', required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' }],
        length: {
          validator: (r, v, cb) => {
            if (!_.isEmpty(v) && !this.$reg.DigitNumber(v, 3, 9)) {
              return cb(this.$tt("tip_check_decimal_digit_int", { digit: 3, int: 9 }))
            }
            cb()
          }, trigger: 'change',
        },
        width: {
          validator: (r, v, cb) => {
            if (!_.isEmpty(v) && !this.$reg.DigitNumber(v, 3, 9)) {
              return cb(this.$tt("tip_check_decimal_digit_int", { digit: 3, int: 9 }))
            }
            cb()
          }, trigger: 'change'
        },
        height: {
          validator: (r, v, cb) => {
            if (!_.isEmpty(v) && !this.$reg.DigitNumber(v, 3, 9)) {
              return cb(this.$tt("tip_check_decimal_digit_int", { digit: 3, int: 9 }))
            }
            cb()
          }, trigger: 'change'
        },
        weight: {
          validator: (r, v, cb) => {
            if (!_.isEmpty(v) && !this.$reg.DigitNumber(v, 3, 9)) {
              return cb(this.$tt("tip_check_decimal_digit_int", { digit: 3, int: 9 }))
            }
            cb()
          }, trigger: 'change'
        },
      },

      batchPackForm: {

      },
      BatchTableOption: {
        height: 450,
        model: [
          { label: 'label_package_code', key: 'packageNo', 'width': 160 },
          { label: '箱数', width: 100, formatter: (r, c, v) => r.boxNoList ? r.boxNoList.length : 0 },
          {
            label: 'label_box_code', width: 140, render: (h, { row }) => {
              if (!row.boxNoList) return
              return (row.boxNoList.map(it => <div>{it}</div>))
            }
          },

          {
            label: 'label_pack_material', 'min-width': 170,
            renderHeader: (h, { column, $index }) => {
              return (
                <span class="table-require">{this.$tt(column.label)}</span>
              )
            },
            render: (h, { row }) => {
              return h('ex_bottom_tip_item', {
                props: {
                  tip: row.error && row.error.packagingId
                },
              }, [
                h(pack_material_cascader, {
                  class: '',
                  props: {
                    packId: row.packagingId,
                    packName: row.packagingName,
                    typeId: row.packagingTypeId,
                    typeName: row.packagingTypeName,
                  },
                  on: {
                    'update:packId': (e) => this.$set(row, 'packagingId', e),
                    'update:packName': (e) => this.$set(row, 'packagingName', e),
                    'update:typeId': (e) => this.$set(row, 'packagingTypeId', e),
                    'update:typeName': (e) => this.$set(row, 'packagingTypeName', e),
                  },
                })
              ])
            }
          },
          {
            label: 'label_check_pack_weight', key: 'weight', 'min-width': 180, render: (h, { row }) => {
              return (<ex_bottom_tip_item tip={row.error && row.error.weight}>
                <ex_super_input size="mini" value={row.weight}
                  placeholder="label_check_pack_weight" append="KG" appendClass="input_slot_div_mini"
                  onInput={e => this.$set(row, 'weight', e.trim())} />
              </ex_bottom_tip_item>)
            }
          },
          {
            label: 'label_check_pack_size', 'min-width': 180, render: (h, { row }) => {
              return (<ex_bottom_tip_item tip={row.error && row.error.dimension}>
                <ex_super_input size="mini" value={row.length}
                  placeholder="label_check_pack_length" append="CM" appendClass="input_slot_div_mini"
                  onInput={e => this.$set(row, 'length', e.trim())} />
                <ex_super_input size="mini" value={row.width}
                  placeholder="label_check_pack_width" append="CM" appendClass="input_slot_div_mini"
                  onInput={e => this.$set(row, 'width', e.trim())} />
                <ex_super_input size="mini" value={row.height}
                  placeholder="label_check_pack_height" append="CM" appendClass="input_slot_div_mini"
                  onInput={e => this.$set(row, 'height', e.trim())} />
              </ex_bottom_tip_item>)
            }
          },

        ]
      },
      BatchPackiRules: {
        packingParamList: {
          required: true,
          trigger: 'change',
          type: "array",
          validator: (r, v, cb) => {
            if (_.isEmpty(v)) {
              return cb(this.$tt('tip_can_no_empty'))
            }

            return cb()
          },
        },
      },
      BatchSchema: new Schema({
        packagingId: { type: 'string', message: this.$tt('tip_can_no_empty'), required: true, },
        weight: {
          type: 'number', required: true, validator: (r, v, cb) => {
            if (!_.isEmpty(v) && !this.$reg.DigitNumber(v, 3, 9)) {
              return cb(this.$tt("tip_check_decimal_digit_int", { digit: 3, int: 9 }))
            }
            cb()
          },
        },
        length: {
          type: 'number', required: true, validator: (r, v, cb) => {
            if (!_.isEmpty(v) && !this.$reg.DigitNumber(v, 2, 9)) {
              return cb(this.$tt("tip_check_decimal_digit_int", { digit: 2, int: 9 }))
            }
            cb()
          },
        },
        height: {
          type: 'number', required: true, validator: (r, v, cb) => {
            if (!_.isEmpty(v) && !this.$reg.DigitNumber(v, 2, 9)) {
              return cb(this.$tt("tip_check_decimal_digit_int", { digit: 2, int: 9 }))
            }
            cb()
          },
        },
        width: {
          type: 'number', required: true, validator: (r, v, cb) => {
            if (!_.isEmpty(v) && !this.$reg.DigitNumber(v, 2, 9)) {
              return cb(this.$tt("tip_check_decimal_digit_int", { digit: 2, int: 9 }))
            }
            cb()
          },
        },
      }),
    }
  },
  props: {

  },
  methods: {
    beforeUpload(file) {
      this.loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
      });
    },
    uploadExcelSuccess(response, file, fileList) {
      if (response.code == 0) {
        console.log(response.data.rows)
        this.$set(this.batchPackForm, 'packingParamList', response.data.rows)
        // this.$message.success('上传成功');
      } else {
        this.$message.error(response.message || '上传错误');
      }
      if (this.$refs.upload) this.$refs.upload.clearFiles()
      if (this.loading) this.loading.close();
    },
    uploadExcelError(response, file, fileList) {
      this.$message.error('上传失败')
      if (this.loading) this.loading.close();
    },
    packingGenerate(call) {
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundTransitPackagingRpc/generatePackageNo.json",
        method: 'post', loading: true,
        success: (res) => {
          this.singlePackForm.packageNo = res.data
          if (call) call(res.data)
        }
      })
    },

    show(rows) {
      let _list = rows
      if (_list.some(it => it.checkoutStatus != 'NOT_CHECKOUT')) {
        return this.$message.error(this.$tt('tip_part_order_status_error_no_operate'))
      }
      this.singlePackForm = _.cloneDeep(default_dialogPackingForm)
      this.singlePackForm.receivingIdList = _list.map(it => it.id)
      this.selectOrderList = _list
      this.batchPackForm = {}
      this.visible = true
      this.packingGenerate()
    },

    okMeasure(data) {
      const has_measure = !_.isEmpty(data.length) && !_.isEmpty(data.width) &&
        !_.isEmpty(data.height) && !_.isEmpty(data.weight)
      const no_measure = _.isEmpty(data.length) && _.isEmpty(data.width) &&
        _.isEmpty(data.height) && _.isEmpty(data.weight)
      return has_measure || no_measure
    },
    submitPackNet() {
      if (this.okMeasure(this.singlePackForm)) {
        this.$ajax({
          url: "/wms-api/inbound/WmsInboundTransitPackagingRpc/packing.json",
          method: 'post', type: 'json', loading: true,
          data: this.singlePackForm,
          success: (res) => {
            this.$message.success(this.$tt('tip_submit_success'))
            this.$emit('success', true)

            this.visible = false
          }
        })
      } else {
        this.$confirm('当前仅有部分测量参数，继续提交将需要重新测量？', this.$tt('label_tip'), {
          type: 'warning'
        }).then(() => {
          const data = _.cloneDeep(this.singlePackForm)
          delete data.weight
          delete data.length
          delete data.width
          delete data.height
          this.$ajax({
            url: "/wms-api/inbound/WmsInboundTransitPackagingRpc/packing.json",
            method: 'post', type: 'json', loading: true,
            data: data,
            success: (res) => {
              this.$message.success(this.$tt('tip_submit_success'))
              this.$emit('success', true)
              this.visible = false
            }
          })
        }).catch(() => {

        });
      }
    },

    submitPackBatchNet() {
      if (this.batchPackForm.packingParamList.every(e => this.okMeasure(e))) {
        this.$ajax({
          url: "/wms-api/inbound/WmsInboundTransitPackagingRpc/batchPacking.json",
          method: 'post', type: 'json', loading: true,
          data: {
            ...this.batchPackForm,
            receivingIdList: this.selectOrderList.map(it => it.id),
          },
          success: (res) => {
            if (res.data.rows) {
              this.batchReturn(res.data.rows)
            } else {
              this.$message.success(this.$tt('tip_submit_success'))
              this.$emit('success', true)
              this.visible = false

            }
          }
        })
      } else {
        this.$confirm('当前仅有部分测量参数，继续提交将需要重新测量？', this.$tt('label_tip'), {
          type: 'warning'
        }).then(() => {
          const list = _.cloneDeep(this.batchPackForm.packingParamList)
          list.forEach(it => {
            delete it.weight
            delete it.length
            delete it.width
            delete it.height
          })
          this.$ajax({
            url: "/wms-api/inbound/WmsInboundTransitPackagingRpc/batchPacking.json",
            method: 'post', type: 'json', loading: true,
            data: {
              packingParamList: list,
              receivingIdList: this.selectOrderList.map(it => it.id),
            },
            success: (res) => {
              if (res.data.rows) {
                this.batchReturn(res.data.rows)
              } else {
                this.$message.success(this.$tt('tip_submit_success'))
                this.$emit('success', true)
                this.visible = false
              }
            }
          })
        }).catch(() => {

        });
      }
    },
    batchReturn(rows) {
      let okList = rows.filter(it => it.success == true)
      const errList = rows.filter(it => it.success == false)
      if (okList.length > 0) {
        this.$message.success(this.$tt('tip_submit_success'))
        this.$emit('success', true)
      }
      if (errList.length == 0) {
        this.visible = false
      } else {
        const list = _.cloneDeep(this.batchPackForm.packingParamList).filter(it => !okList.some(ok => ok.packageNo == it.packageNo))
        this.batchPackForm.packingParamList = list
        this.$msgbox_table({
          note: this.$tt('label_pack_failed_to_operate'),
          tableProp: {
            data: errList,
            model: [
              { key: 'packageNo', label: 'label_package_code', 'min-width': 120, 'show-overflow-tooltip': true, },
              { key: 'msg', label: 'label_info', 'min-width': 120, 'show-overflow-tooltip': true, }
            ],
          },
        }, { type: 'error', customClass: 'dialog_small' })
      }

    },
    submitPack() {
      if (this.$clickFast()) return

      if (this.activeTab == 'single') {
        this.$refs['packForm'].validate((valid) => {
          if (valid) {
            this.submitPackNet()
          } else {
            this.$message.error(this.$tt('form_validate_error'))
            return false;
          }
        });
      } else {
        this.$refs['batchForm'].validate((valid) => {
          if (valid) {
            let check = true
            this.batchPackForm.packingParamList.forEach(it => {
              this.BatchSchema.validate(it, (errors, fields) => {
                this.$set(it, 'error', {})
                if (errors) {
                  errors.forEach(er => {
                    let error_name = er.field
                    if (['length', 'height', 'width'].includes(error_name)) error_name = 'dimension'
                    this.$set(it.error, error_name, er.message)
                  })
                  check = false
                }
              })
            })
            if (check) {
              this.submitPackBatchNet()
            }
            return
          } else {
            this.$message.error(this.$tt('form_validate_error'))
            return false;
          }
        });
      }

    },

    packingBoxAdd() {
      if (_.isEmpty(this.packTempBoxNumber)) {
        return this.$message.error(this.$tt("tip_box_code_no_empty"))
      }
      if (this.singlePackForm.boxNoList.some(it => it == this.packTempBoxNumber)) {
        return this.$message.error(this.$tt("tip_box_code_no_repeat"))
      }
      this.singlePackForm.boxNoList.push(this.packTempBoxNumber)
    },

  }
}
</script>
